<template>
  <div class="containner">
    <div class="mainBox" ref="scrollContainer" @scroll="scrollFun">
      <div class="nav-crumbs spf-link">
        <ul class="nav_list">
          <li class="nav_list_item">
            <HomeFilled class="icon_home" />
            <a class="href" href="/">首页</a>
            <ArrowRight class="icon_home" />
          </li>
          <li class="nav_list_item">
            <a class="href" href="/ziYclassrooms" title="讲堂">讲堂</a>
            <ArrowRight class="icon_home" />
          </li>
          <li class="nav_list_item">
            <span>{{ detailDataList?.name }}</span>
          </li>
        </ul>
      </div>
      <!-- 视频区域 -->
      <div class="classroomsDetaiHead">
        <div class="classRoomMain">
          <div class="classRoomLeft">
            <video
              class="video"
              :class="{ className: scrollTop >= 500 }"
              ncontextmenu="false"
              style="padding-top: 10px"
              ref="videoPlayer"
              width="869"
              height="490"
              controls
              :src="currentVideo"
              :poster="currentImg"
              @play="onPlay"
              @pause="onPause"
              @ended="onEnded"
              @loadedmetadata="onLoadedMetadata"
              controlsList="nodownload "
            ></video>

            <CloseBold
              class="del"
              v-if="scrollTop >= 500 && isDel"
              @click="delAction"
              ref="domDel"
            />
          </div>
          <div class="classRoomRight">
            <span class="section-count"
              >共 {{ strArr(detailDataList.videos) }} 讲</span
            >
            <div
              class="section-wrapper"
              v-for="item in videoList"
              :key="item.id"
              @click="changeVideo(item)"
            >
              <div class="section-wrapper_cover_left">
                <div class="section-cover">
                  <ProcessedImage
                    class="grid_img"
                    :src="item.cover"
                    v-if="item.cover"
                    params="imageView2/2/w/84/h/56"
                  />
                </div>
              </div>
              <div class="section-wrapper_right">
                <p class="section-title">
                  {{ item.name }}
                </p>
                <p class="section-friendlyDuration">
                  <span>{{ item.video_time?.replace(/'/g, '') ?? '' }}</span>
                  <span
                    v-if="detailDataList.viewing_permission == 3"
                    class="look"
                    >{{
                      detailDataList?.is_verify
                        ? '已付费'
                        : item.tryLook
                          ? '免费'
                          : '付费'
                    }}</span
                  >
                  <span
                    v-else-if="detailDataList.viewing_permission == 1"
                    class="look"
                    >免费
                  </span>
                  <span v-else class="look">VIP独享</span>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--  -->
      <div class="classroomsTitle">
        <div class="classroomsTitleLeft">
          <span class="classroomstxt">{{ detailDataList.name }}</span>
          <span class="classroomsWatchType">{{
            permission[detailDataList.viewing_permission]
          }}</span>
        </div>
        <p class="classroomsDescription">
          {{ detailDataList.describe }}
        </p>
        <div class="classroomsTags">
          <span class="classroomsHits"
            >{{ detailDataList.videoNum ?? 0 }}播放</span
          >
          <a
            @click="pre"
            class="pull-left"
            v-if="
              get(typeName, '[0].name', '') &&
              get(typeName, '[0].name', '') != '不限'
            "
            >{{ get(typeName, '[0].name', '') }}</a
          >
        </div>
      </div>

      <div class="wrapper-title">
        <div class="left"></div>
        <div class="right">相关课程</div>
      </div>

      <div class="packsData">
        <div class="ziYuanBox">
          <div class="grid-container">
            <div
              class="grid-item"
              @click="detailItem(item)"
              v-for="item in tableData"
              :key="item.id"
            >
              <div class="coverUrl">
                <ProcessedImage
                  class="grid_img"
                  :src="item.cover"
                  :title="item.name"
                  params="imageView2/2/w/216/h/144"
                  v-if="item.cover"
                />
                <div class="sectionCount">共{{ strArr(item.videos) }}讲</div>
              </div>

              <div style="padding: 10px">
                <p class="grid_txt">
                  <span v-if="item.sign">{{ SIGN_NAME[item.sign] + '-' }}</span>
                  <span>{{ item.name }}</span>
                </p>
                <div class="sign_box">
                  <p class="grid_txt" style="color: #999">
                    {{ item.videoNum ?? 0 }} 播放
                  </p>
                  <p class="grid_txt" style="color: #e84c34; font-size: 24px">
                    <i
                      v-if="item.viewing_permission == 1"
                      class="iconfont icon-mianfei-xianxing"
                    ></i>
                    <i
                      v-if="item.viewing_permission == 2"
                      class="iconfont icon-VIP"
                    ></i>
                    <i
                      v-if="item.viewing_permission == 3"
                      class="iconfont icon-menzhenshoufei"
                    ></i>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="">
        <zyBottom></zyBottom>
      </div>
    </div>
    <!-- 判断是否会员 -->
    <isVipDialog ref="isVipDialogShow" />
    <!-- 支付弹框 -->
    <Dialog
      v-model="modelValue"
      width="840"
      @closePayDialog="closePayDialog"
      @openClick="openClick"
    >
      <template #content>
        <div class="padding">
          <pay
            ref="payRerf"
            :detailList="detailList"
            :codeUrl="code_url"
            :formattedTime="formattedTime"
            :imgLoading="imgLoading"
            :resultPrice="resultPrice"
            :bannerInfoList="bannerInfoList"
            @payAll="payAll"
            @changePay="changePay"
          ></pay>
        </div>
        <!-- <div class="qrcode" v-loading="imgLoading" width="600">
          <img :src="code_url" alt="" class="qrImage" />
          <p>{{ goodsName }}</p>
          <p>{{ formattedTime }}</p>
        </div> -->
      </template>
    </Dialog>
  </div>
</template>
<script setup>
import pay from '@/components/ziYuanLectureHall/components/payment_tab/index.vue';
import isVipDialog from '@/components/Dialog/isVipDialog';
import QRCode from 'qrcode';
import zyBottom from '@/components/ziYuanLectureHall/components/index.vue'; //infoApi
import Dialog from '@/components/Dialog/payDialog.vue';
import {
  infoApi,
  getvideoListApi,
  classTypeListApi,
  singleCoursePayApi,
  verifyApi,
  AlipayToolApi,
  bannerInfoyApi,
} from '@/api/zy/index';
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { get } from 'lodash';
import { useStore } from 'vuex';
import { useNavigation } from '@/hooks/useNavigation';
const { goTo } = useNavigation();
const store = useStore();
const route = useRoute();
const detailDataList = ref([]);
const isVipDialogShow = ref(null);
// 当前播放的视频
const videoPlayer = ref(null);
const domDel = ref(null);
const isDel = ref(true);
const currentVideo = ref('');
const currentImg = ref('');
const detailList = ref({});
const resultPrice = ref([]);
const bannerInfoList = ref([]);
//const currentTime = ref(0); //播放时间
// const minutes = ref('');
// const seconds = ref('');
const videoList = ref([]);
const tableData = ref([]);
const typeName = ref('');
const modelValue = ref(false);
const timeRemaining = ref(300); // 倒计时时间，单位：秒（5 分钟）
const imgLoading = ref(false);
const code_url = ref('');
const out_trade_no = ref('');
const scrollContainer = ref(null);
// const goodsName = ref('');
const paymentStatus = ref(''); // 支付状态：空、success、failed
const statusPay = ref(true);
const scrollTop = ref(null);
const tableConfig = ref({
  page: 1,
  pageSize: 10,
  type: '',
  status: '',
  viewing_permission: '',
});
const filterOptions = ref([
  {
    id: 38,
    pid: 0,
    name: '课程主题',
    type: 3,
    childs: [],
  },
  {
    id: 41,
    pid: 0,
    name: '课程价格',
    type: 2,
    childs: [
      { id: 1, name: '免费' },
      { id: 2, name: 'vip' },
      { id: 3, name: '收费' },
    ],
  },
]);
const SIGN_NAME = {
  1: '选修',
  2: '必修',
};
const classParams = ref({
  page: 1,
  pageSize: 100,
});
const permission = ref({
  1: '免费',
  2: 'vip',
  3: '收费',
});
const payRerf = ref(null);
const closePayDialog = () => {
  payRerf.value.toggleText('false');
  payRerf.value.switchPayment('true');
  stopPolling();
};
const openClick = () => {
  payRerf.value.checkOverflow();
};
// 课程类别
const classTypeList = async () => {
  const { data } = await classTypeListApi(classParams.value);
  resultPrice.value = data.data;
  filterOptions.value[0].childs = data.data.data;
  filterOptions.value[0].childs.unshift({ id: 0, name: '不限' });
  typeName.value = filterOptions.value[0].childs.filter(
    (item) => item.id == tableConfig.value.type,
  );
};
const infoData = async (id) => {
  const { data } = await infoApi({ id });
  detailDataList.value = data.data;
  videoList.value = JSON.parse(get(detailDataList.value, 'videoSort', '[]'));
  // 将 tryLook 为 true 的对象放到前面
  const sortedData = videoList.value.sort(
    (a, b) => (b.tryLook === true ? 1 : 0) - (a.tryLook === true ? 1 : 0),
  );

  // 播放第一个视频
  currentVideo.value = get(sortedData, '[0].add', []);
  // 第一个封面
  currentImg.value = get(sortedData, '[0].cover', []);
};
// 处理数据
const strArr = (item) => {
  return item ? item.split(',').length : 0;
};
// 切换视频
const changeVideo = async (item) => {
  if (
    item.tryLook ||
    detailDataList.value.is_verify ||
    detailDataList.value.viewing_permission == 1 ||
    detailDataList.value.viewing_permission == 2
  ) {
    currentVideo.value = item.add;
    currentImg.value = item.cover;
  } else {
    detailList.value = detailDataList.value;
    modelValue.value = true;
    imgLoading.value = true;
    code({ id: route.query.id, type: 1 });
  }
};
// 筛选课程
const onPlay = () => {
  console.log('视频开始播放');
};

const onPause = () => {
  console.log('视频暂停');
};

const onEnded = () => {
  console.log('视频播放结束');
};
// 播放总时长
// const onLoadedMetadata = (event) => {
//   currentTime.value = Math.floor(event.target.duration);
//   formatTime(currentTime.value);
// };
// const formatTime = (time) => {
//   minutes.value = zero(Math.floor(time / 60));
//   seconds.value = zero(Math.floor(time % 60));
// };
// // 补零操作
// const zero = (item) => {
//   return (item = item < 10 ? '0' + item : item);
// };
// 倒计时格式化为分钟和秒
const formattedTime = computed(() => {
  const minutes = Math.floor(timeRemaining.value / 60);
  const seconds = timeRemaining.value % 60;
  return (
    '请在' +
    `${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}` +
    '秒内完成支付'
  );
});
// 当前课程信息
const detailItem = async (item) => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollTo({
      top: 0,
      behavior: 'smooth', // 平滑滚动
    });
  }
  const isVIP = store.getters.user.userInfo.isVIP;
  const { viewing_permission } = item;
  if ((isVIP && viewing_permission == 2) || viewing_permission == 1) {
    // 播放第一个视频
    currentVideo.value = get(videoList.value, '[0].add', []);
    // 第一个封面
    currentImg.value = get(videoList.value, '[0].cover', []);
    detailDataList.value = item;
    videoList.value = JSON.parse(get(item, 'videoSort', []));
    goTo('/ziYclassroomsDetail', {
      query: { id: item.id, type: item.type, status: item.status },
    });
  } else if (item.viewing_permission == 2) {
    isVipDialogShow.value.openDialog();
  } else if (viewing_permission == 3) {
    if (item.is_verify) {
      // 播放第一个视频
      currentVideo.value = JSON.parse(get(item, 'videoSort', '[]'))[0].add;
      // 第一个封面
      currentImg.value = item.cover;
      detailDataList.value = item;
      videoList.value = JSON.parse(get(item, 'videoSort', []));
    } else {
      detailList.value = item;
      modelValue.value = true;
      imgLoading.value = true;
      code({ id: item.id, type: 1 });
    }
  } else {
    isVipDialogShow.value.openDialog();
  }
};
const code = async (params) => {
  const data = statusPay.value
    ? await singleCoursePayApi(params)
    : await AlipayToolApi(params);
  if (data.data.code == 20000) {
    out_trade_no.value = data.data.data.out_trade_no;
    QRCode.toDataURL(data.data.data.code_url)
      .then((url) => {
        code_url.value = url;
        timeRemaining.value = 300; // 重置倒计时
        startCountdown(); // 开始倒计时
        startPolling(); // 开始轮询
        imgLoading.value = false;
      })
      .catch((error) => {
        console.error('二维码生成失败:', error);
      });
  }
};
const payAll = (val) => {
  // 购买全部课程
  code(val);
};
// 切换支付
const changePay = ({ params, index }) => {
  statusPay.value = !statusPay.value;
  index == 0 ? code({ id: detailList.value.id, type: 1 }) : code(params);
};
// 倒计时逻辑
let countdownInterval;
const startCountdown = () => {
  clearInterval(countdownInterval); // 清除之前的倒计时
  countdownInterval = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value -= 1;
    } else {
      clearInterval(countdownInterval); // 倒计时结束时停止计时
      stopPolling(); // 停止轮询
    }
  }, 1000);
};

// 轮询支付状态逻辑
let pollingInterval;
const startPolling = () => {
  clearInterval(pollingInterval); // 清除之前的轮询
  pollingInterval = setInterval(async () => {
    try {
      const response = await verifyApi({ out_trade_no: out_trade_no.value }); // 模拟后端请求
      if (response.data.msg === '购买成功') {
        paymentStatus.value = '购买成功';
        clearInterval(pollingInterval); // 停止轮询
        clearInterval(countdownInterval); // 停止倒计时
        tableDataList();
        infoData(route.query.id);
        modelValue.value = false;
      }
    } catch (error) {
      console.error('轮询支付状态失败:', error);
    }
  }, 5000); // 每 5 秒轮询一次
};

// 停止轮询
const stopPolling = () => {
  clearInterval(pollingInterval);
};

// 视频列表
const tableDataList = async () => {
  try {
    const { data } = await getvideoListApi(tableConfig.value);
    tableData.value = data.data.data;
    tableData.value = tableData.value.filter((item) => item.status == 1);
  } catch (err) {
    console.log(err);
  }
};
const pre = () => {
  goTo('/ziYclassrooms', { query: { type: tableConfig.value.type } });
};
const bannerInfo = async () => {
  const data = await bannerInfoyApi();
  bannerInfoList.value = data.data.data;
};
// 处理滚动事件
const scrollFun = (e) => {
  scrollTop.value = e.target.scrollTop;
  if (scrollTop.value <= 500) isDel.value = true;
  // 如果需要，进一步处理滚动事件，如懒加载等
};
const delAction = () => {
  isDel.value = false;
  videoPlayer.value.classList.remove('className'); //del 删除类名\
  domDel.value.classList?.add('noneCss');
  console.log(domDel.value, 'video');
};
onMounted(() => {
  bannerInfo();
  if (route.query.id) {
    infoData(route.query.id);
    Object.assign(tableConfig.value, route.query);
    delete tableConfig.value.id;
  }
  tableDataList();
  classTypeList();
  const videoElement = document.querySelector('video');
  videoElement.addEventListener('contextmenu', (e) => {
    e.preventDefault(); // 禁止右键菜单
  });
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
